package com.zhongzhi.javafx.controller;

import java.net.URL;
import java.util.ResourceBundle;

import com.zhongzhi.common.Common;
import com.zhongzhi.util.ClientUtil;
import com.zhongzhi.util.JsonResult;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import lombok.extern.log4j.Log4j;
import javafx.scene.control.TextArea;

@Log4j
public class ComputersNewController implements Initializable{
	@FXML
	private TextField computersName;
	@FXML
	private TextField computers;
	@FXML
	private TextField computersIP;
	@FXML
	private TextArea remarks;
	@FXML
	private Button stop;
	@FXML
	private Button add;
    @FXML
    private Label textts;
    
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		log.info("新增计算机窗口:开始初始化");
		//关闭窗口
		stop.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				Stage window = (Stage) stop.getScene().getWindow();
				window.close();
			}
		});
		//添加窗口
		add.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				log.info("新建设备窗口:按下确定按钮");
				if (computersName.getText()==null || computersName.getText().equals("")) {
					textts.setText("计算机名称不能为空");
				}else if (computers.getText()==null || computers.getText().equals("")) {
					textts.setText("计算机站号不能为空");
				}else if (computersIP.getText().matches("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}")==false) {
					textts.setText("计算机ip地址格式不正确");
				}else {
					int a=0;
					try {
						
							insert();
						
					} catch (Exception e) {
						a=2000;
						textts.setText("端口必须为纯数字");
					}

				}
			}

			
		});
		if (remarks.getText()==null || remarks.getText().equals("")) {
			remarks.setText("无");
		}
		log.info("新增计算机窗口:初始化完成");
	}

	private void insert() {
		
		try {
			String s = "http://127.0.0.1:8080/computers/insert?id=0&name=" + computersName.getText().trim()
					+ "&computers=" + computers.getText().trim()
					+ "&computersip=" + computersIP.getText().trim()
					+ "&remarks=" + remarks.getText().trim();
					
					log.info("新增计算机窗口:发送新增设备请求:"+s);
					String gethttp = ClientUtil.Gethttp(s);
					log.info("新增计算机窗口:新增设备请求返回数据:"+gethttp);
					JsonResult jsonobj = ClientUtil.Jsonobj(gethttp, JsonResult.class);
					if (jsonobj.getCode()==200) {
						ScrollPane sp = Common.getSp();
						sp.setContent(FXMLLoader.load(getClass().getResource("/fxml/run/computers.fxml")));
						
						Stage window = (Stage) stop.getScene().getWindow();
						window.close();
					}else {
						textts.setText(jsonobj.getMessage());
					}
		} catch (Exception e) {
			log.error("新增计算机窗口:新增设备请求返回数据失败:"+e);
		}
		
	}
}
